<template>
	<div class="app-container">
		<div class="header">
			<div>
				<p>会议号：{{ roomId }}</p>
				<!-- <p>
          邀请人数：{{ videoList.length }}人 参会人数：{{
            showVideoList.length
          }}人
        </p> -->
			</div>
			<div>
				<el-button type="primary" :style="{ opacity: videoType == 0 ? '1' : '0.5' }" plain @click="videoType = 0">
					2X2</el-button>
				<el-button type="success" :style="{ opacity: videoType == 1 ? '1' : '0.5' }" plain @click="videoType = 1">
					4X4</el-button>
				<el-button type="danger" :style="{ opacity: videoType == 2 ? '1' : '0.5' }" plain @click="videoType = 2">
					小窗排列</el-button>
				<!-- 	<el-button type="danger" :style="{ opacity: videoType == 2 ? '1' : '0.5' }" plain @click="videoType = 3">
					放大某一项</el-button> -->
			</div>
			<div>
				<el-button type="primary" @click="toggleMuteAllRemoteAudio">
					<i v-if="isMuteAllRemoteAudio == false">&nbsp;&nbsp;全部静音&nbsp;&nbsp;</i>
					<i v-if="isMuteAllRemoteAudio == true">&nbsp;&nbsp;解除静音&nbsp;&nbsp;</i>
				</el-button>
				<el-button type="primary" @click="toggleMic">
					<i v-if="isMuteMic == false">&nbsp;&nbsp;静&nbsp;&nbsp;&nbsp;音&nbsp;&nbsp;</i>
					<i v-if="isMuteMic == true">&nbsp;&nbsp;解除静音&nbsp;&nbsp;</i>
				</el-button>
				<el-button type="primary" @click="toggleCamera"><i v-if="isDisableCamara == false">关闭视频</i>
					<i v-if="isDisableCamara == true">打开视频</i>
				</el-button>
				<el-button type="primary" @click="toggleScreenSharing"><i v-if="isScreenSharing == false">屏幕分享</i>
					<i v-if="isScreenSharing == true">结束分享</i>
				</el-button>
				 <el-button type="primary" v-if="showRequestPeoples == true" @click="centerDialogVisible = true">邀请参会</el-button> 
				<el-button type="warning" @click="exitRoom">离开会议</el-button>
				 <el-button type="primary"  v-if="showEndMeeting == true"   @click="cloudRecord">{{isCloudRecord==true?'结束云录制':'开始云录制'}}</el-button> 
				 <el-button type="danger"  v-if="showEndMeeting == true"   @click="endRoom">结束会议</el-button> 
			</div>
		</div>
		
		<div class="video-box" id="video-container">
			<div v-for="(item, key) in videoList" :key="key" :id="key" :ref="'video'+key" :class="
          videoKey != null && videoKey == key
            ? 'showItem'
            : videoType == 0
            ? 'two'
            : videoType == 1
            ? 'four'
            : 'all'
        "></div>
		</div>
		<el-dialog title="邀请参会人员" :visible.sync="centerDialogVisible" width="90%" center>
			<el-row :gutter="20">
				<el-col :span="8" :xs="24">
					<el-tree :data="treeData" show-checkbox node-key="id" :check-strictly="true" default-expand-all
						:default-expanded-keys="[2, 3]" :default-checked-keys="[5]" :props="defaultProps"
						@check="treeCheck" ref="tree">
					</el-tree>
				</el-col>
				<el-col :span="16" :xs="24">
					<el-row :gutter="10" class="mb8">
						<el-col :span="1.5">
							<el-button type="primary" plain icon="el-icon-guide"   @click="handleSendRequest">
								发送会议邀请</el-button>
						</el-col>
						<el-col :span="1.5">
							<el-button type="primary" plain     @click="handleCancel">取消
							</el-button>
						</el-col>
					</el-row>

					<el-table :data="userList" @selection-change="handleSelectionChange">
						<el-table-column type="selection" width="50" align="center" />
						<!-- <el-table-column
              label="用户编号"
              align="center"
              key="userId"
              prop="userId"
            /> -->
						<el-table-column label="用户名称" align="center" key="userName" prop="userName"
							:show-overflow-tooltip="true" />
						<el-table-column label="用户昵称" align="center" key="nickName" prop="nickName"
							:show-overflow-tooltip="true" />
						<el-table-column label="部门" align="center" key="deptName" prop="dept.deptName"
							:show-overflow-tooltip="true" />
						<el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
					</el-table>

					<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
						:limit.sync="queryParams.pageSize" @pagination="getUserList" />
				</el-col>
			</el-row>
		</el-dialog>
		<el-dialog id="screens-list-modal" :visible.sync="screensListVisiable" title="可分享的窗口">
			<show-screen-capture :list="screensList" :on-click="chooseWindowCapture" />
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import {
		ticket
	} from "@/api/trtc";
	import {
		treeselect
	} from "@/api/system/dept";
	import {
		listUser
	} from "@/api/system/user";
	import {
		addMeeting,updateMeeting,startMCUMixTranscode,stopMCUMixTranscode
	} from "@/api/system/meeting";
	import TRTCCloud from "trtc-electron-sdk";
	import showScreenCpature from "@/components/show-screen-capture";
	import trtcState from "@/common/trtc-state";
	import Log from "@/common/log";
	const logger = new Log(`trtcRoom`);
	import {
		TRTCAppScene,
		TRTCVideoStreamType,
		TRTCVideoFillMode,
		TRTCParams,
		TRTCVideoEncParam,
		TRTCVideoResolution,
		TRTCVideoResolutionMode,
		TRTCBeautyStyle,
		Rect,
	} from "trtc-electron-sdk/liteav/trtc_define";
	import {
		BDVideoEncode,
		BDBeauty
	} from "../../common/bd-tools";
	let trtcCloud = null; // 用于TRTCQcloud 实例， mounted 时实体化
	export default {
		components: {
			"show-screen-capture": showScreenCpature,
		},
		data() {
			return {
				videoKey: null,
				treeData: [],
				centerDialogVisible: false,
				videoType: 0,
				videoList: [{}],
				videoListIndex: 1,
				showVideoList: [],
				select: "",
				defaultProps: {
					children: "children",
					label: "label",
				},
				currentCheckData: {}, // 当前选中的值
				userList: [],
				total: 0,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					userName: undefined,
					phonenumber: undefined,
					status: undefined,
					deptId: undefined,
				},
				selected_user_nums: [],
				meetingInfo: {
          id:0,
					status: 0,
					masterId: 0,
					meetingName: "",
					beginTime: null,
					meetingRoomId: "",
					meetingMembers: "",
				},
        showEndMeeting:false,
        showRequestPeoples:false,
		isCloudRecord:false,

				roomId: 12345678,
				cameraId: "",
				cameraList: [],
				videosList: [],
				streamType: TRTCVideoStreamType.TRTCVideoStreamTypeBig,
				isMuteMic: false,
				isDisableCamara: false,
				isScreenSharing: false,
				getScreensTaskID: 0,
				screensList: [],
				screensListVisiable: false,
				videoContainer: null,
				sdkInfo: null,
				// 存放远程用户视频列表
				remoteVideos: {},
				isRemoteScreenSharing: false, // 远程用户是否正在分享屏幕
				isMuteAllRemoteAudio:false,//是否静音掉所有远端用户的声音， 
			};
		},
		computed: {
			...mapGetters(["userId"]),
			...mapGetters(["userObj"]),
		},
		created() {
			this.loadTreedata();
			this.getUserList();
		},
		methods: {
			cloudRecord(){
				// let m = {meetingRoomId:this.roomId}
				let m = {meetingRoomId:this.roomId,id:this.meetingInfo.id}
				this.isCloudRecord=!this.isCloudRecord
				if(this.isCloudRecord){
					startMCUMixTranscode(m).then(res=>{
						console.log(res)
					})
				}else{
					stopMCUMixTranscode(m).then(res=>{
						console.log(res)
					})
				}

			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.selected_user_nums = selection.map((item) => item.phonenumber);
				console.log(this.selected_user_nums);
			},
			handleCancel() {
				this.centerDialogVisible = false;
			},
			//发送会议邀请
			handleSendRequest() {
				if (this.selected_user_nums.length == 0) {
					this.$message({
						message: "没有选择人员",
						type: "warning",
					});
					return;
				}
				this.meetingInfo.masterId = this.userId
				this.meetingInfo.meetingName = this.userObj.nickName + "发起的快速会议"
				this.selected_user_nums.push(this.userObj.phonenumber) //把自己加入会议人员名单
				this.meetingInfo.meetingMembers = this.selected_user_nums.toString()
				this.meetingInfo.meetingRoomId = this.roomId
				addMeeting(this.meetingInfo).then((response) => {
					console.log(response)
					this.$message({
						message: "已通过短信发送会议邀请",
						type: "success",
					});
					this.centerDialogVisible = false;
          this.showRequestPeoples = false;
				});
			},
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getUserList();
			},
			/** 查询用户列表 */
			getUserList() {
				listUser(this.queryParams).then((response) => {
					this.userList = response.rows;
					this.total = response.total;
				});
			},
			// treeCheck(nodeObj, selectObj) {
			treeCheck(data) {
				if (this.currentCheckData.id === data.id) {
					this.currentCheckData = {};
					this.$refs.tree.setCheckedKeys([]);
				} else {
					this.currentCheckData = data;
					this.$refs.tree.setCheckedKeys([data.id]);
				}
				this.queryParams.deptId = this.currentCheckData.id;
				this.getUserList();
			},
			loadTreedata() {
				treeselect().then((response) => {
					this.treeData = response.data;
				});
			},
			backRoom() {
				this.$router.push("/index");
			},
			get_ticket() {
				//获取客户票据
				ticket({
					userId: this.userId,
				}).then((response) => {
					const {
						data
					} = response;
					this.sdkInfo = data;
				});
			},
			/**
			 * SDK 不可恢复的错误，一定要监听，并分情况给用户适当的界面提示。
			 */
			onError(errCode, errMsg) {
				logger.error(`SDK onError: ${errCode} ${errMsg}`);
				window.appMonitor?.reportEvent(
					"EnterVideoRoom",
					`failed#error:${errCode} ${errMsg}`
				);
			},

			/**
			 * 用于告知您一些非严重性问题，例如出现了卡顿或者可恢复的解码失败。
			 */
			onWarning(warningCode, warningMsg) {
				logger.warn(`SDK onWarning: ${warningCode} ${warningMsg}`);
			},

			/**
			 * 当进入房间时触发的回调
			 * @param {number} result - 进房结果， 大于 0 时，为进房间消耗的时间，这表示进进房成功。如果为 -1 ，则表示进房失败。
			 **/
			onEnterRoom(result) {
				if (result > 0) {
					logger.log(`onEnterRoom，进房成功，使用了 ${result} 毫秒`);
					// 显示摄像头，开房麦克风，开始推流
					this.startCameraAndMic();
				} else {
					logger.warn(`onEnterRoom: 进房失败 ${result}`);
				}
			},

			/**
			 * 当退出房间时触发的回调
			 */
			onExitRoom(reason) {
				logger.warn(`onExitRoom, reason: ${reason}`);
			},

			/**
			 * 远程用户视频流的状态发生变更时触发。
			 * @param {number} uid - 用户标识
			 * @param {boolean} available - 画面是否开启
			 **/
			onUserVideoAvailable(uid, available) {
				logger.log(`onUserVideoAvailable: uid: ${uid}, available: ${available}`);
				if (available === 1) {
					this.showVideo(uid);
				} else {
					this.closeVideo(uid);
				}
			},

			/***
			 * 显示其他用户的视频
			 * @param {number} uid - 用户ID
			 */
			showVideo(uid) {
				logger.warn("显示其他用户的视频", uid);
				//   let id = `${uid}-${this.roomId}-${TRTCVideoStreamType.TRTCVideoStreamTypeBig}`;
				//   let view = document.getElementById(id);
				//   if (!view) {
				//     view = document.createElement("div");
				//     view.id = id;
				//     this.videoContainer.appendChild(view);
				//   }
				//   view.style.width = `${this.subStreamWidth}px`;
				//   view.style.height = `${this.subStreamHeight}px`;
				console.log(this.videoList)
				let view;
				if (this.remoteVideos[uid]) {
					view = this.remoteVideos[uid];
					view.style.display = "inline-block";
					this.setVideo()
					this.setVideo(uid, view)
				} else {
					this.videoList.push({})
					setTimeout(() => {
						view = document.getElementById(this.videoListIndex);
						this.videoListIndex++;
						this.remoteVideos[uid] = view;
						this.setVideo(uid, view) //为避异步免生成标签找不到id 走这个方法。
					}, 300)
				}
				console.log("view");
				console.log(view);
				//   this.videoTypeSetting();
			},
			//v-for动态生成标签有渲染时间，添加后无法立即获取，遂添加500毫秒的延迟以便能获取到元素ID
			setVideo(uid, view) {
				trtcCloud.startRemoteView(uid, view);
				trtcCloud.setRemoteViewFillMode(
					uid,
					TRTCVideoFillMode.TRTCVideoFillMode_Fill
				);
			},
			/**
			 * 关闭其他用户的视频
			 * @param {number} uid
			 */
			closeVideo(uid) {
				//   let id = `${uid}-${this.roomId}-${TRTCVideoStreamType.TRTCVideoStreamTypeBig}`;
				//   let view = document.getElementById(id);
				//   if (view) {
				//     this.videoContainer.removeChild(view);
				//   }
				let view = this.remoteVideos[uid];
				view.style.display = "none";
				//   delete this.remoteVideos[uid];
			},

			/**
			 * 当远端用户进入本房间，创建对应对应的画面。
			 */
			onRemoteUserEnterRoom(uid) {
				logger.warn("onRemoteUserEnterRoom", uid);
			},

			/**
			 * 当远端用户离开本房间时，关闭对应的画面。
			 */
			onRemoteUserLeaveRoom(uid) {
				logger.warn("onRemoteUserLeaveRoom", uid);
				this.closeVideo(uid);
			},

			/**
			 * 当远程用户屏幕分享的状态发生变化，会根据 available 参数打开或关闭画面
			 **/
			onUserSubStreamAvailable(uid, available) {
				logger.log(`onUserSubStreamAvailable: ${uid}, ${available}`);
				if (available) {
					this.showRemoteScreenSharing(uid);
					this.isRemoteScreenSharing = true;
				} else {
					this.closeRemoteScreenSharing(uid);
					this.isRemoteScreenSharing = false;
				}
			},

			/**
			 * 显示远程用户的屏幕分享
			 */
			showRemoteScreenSharing(uid) {
				let id = `${uid}-${this.roomId}-${TRTCVideoStreamType.TRTCVideoStreamTypeSub}`;
				logger.log(`showRemoteScreenSharing:  uid: ${id}`);
				let W = this.subStreamWidth;
				let H = this.subStreamHeight;
				let view = document.getElementById(id);
				if (!view) {
					view = document.createElement("div");
					view.id = id;
					view.style.width = `${W}px`;
					view.style.height = `${H}px`;
					this.videoContainer.appendChild(view);
				}
				this.remoteVideos[id] = view;
				trtcCloud.startRemoteSubStreamView(uid, view);
				trtcCloud.setRemoteSubStreamViewFillMode(
					uid,
					TRTCVideoFillMode.TRTCVideoFillMode_Fill
				);
				this.videoTypeSetting();
			},

			/**
			 * 关闭远程用户的屏幕分享
			 *
			 * @param {*} uid
			 */
			closeRemoteScreenSharing(uid) {
				let id = `${uid}-${this.roomId}-${TRTCVideoStreamType.TRTCVideoStreamTypeSub}`;
				let view = document.getElementById(id);
				if (view) {
					this.videoContainer.removeChild(view);
				}
				delete this.remoteVideos[id];
			},

			/**
			 * 对视频元素进行排版
			 */
			videoTypeSetting() {
				let marginTop = 80;
				let margin = 5;
				let H = this.subStreamHeight;
				let m = 0;
				let topIndex = 0;
				let remoteVideos = this.remoteVideos;
				let typeClassName = "";
				let top = 0;
				let i = 0;
				for (let id in remoteVideos) {
					topIndex = Math.floor(i / 2);
					typeClassName = i % 2 === 0 ? "right" : "left";
					top = topIndex * H + (topIndex + 1) * margin + marginTop;
					remoteVideos[id].className = `user-video-container ${typeClassName}`;
					remoteVideos[id].style.top = `${top}px`;
					logger.log(
						`videoTypeSetting: i:${i}, ti: ${topIndex}, top ${top}, H: ${H}, m: ${m}, id:${id},`
					);
					i++;
				}
			},
			/**
			 * 开启 / 关闭 全体静音
			 */
			toggleMuteAllRemoteAudio(event){
				this.isMuteAllRemoteAudio = !this.isMuteAllRemoteAudio;
				trtcCloud.muteAllRemoteAudio(this.isMuteAllRemoteAudio);
				logger.log("toggleMuteAllRemoteAudio", this.isMuteAllRemoteAudio, event);
			},
			/**
			 * 开启 / 关闭麦克风
			 */
			toggleMic(event) {
				this.isMuteMic = !this.isMuteMic;
				trtcCloud.muteLocalAudio(this.isMuteMic);
				logger.log("toggleMic", this.isMuteMic, event);
			},

			/**
			 * 开启 / 关闭摄像头
			 */
			toggleCamera(event) {
				this.isDisableCamara = !this.isDisableCamara;
				if (this.isDisableCamara === true) {
					this.hideLocalCameraVideoDom();
				} else {
					this.startCameraAndMicDom();
				}
				trtcCloud.muteLocalVideo(this.isDisableCamara);
				logger.log("toggleCamera", this.isDisableCamara, event);
			},

			/**
			 * 开启 / 关闭屏幕分享，开启时会弹出窗口选择列表
			 */
			toggleScreenSharing() {
				if (this.isRemoteScreenSharing === true) {
					this.$bvToast.toast(`其他主播正在分享屏幕，您现在无法分享。`, {
						variant: "warning",
					});
					return;
				}
				if (this.isScreenSharing === false) {
					this.getScreensList();
					return;
				}
				this.isScreenSharing = false;
				this.stopScreenShare();
			},

			/**
			 * 获取窗口列表，用于屏幕分享
			 */
			getScreensList() {
				// 获取窗口快照，这是资源消耗很高的函数，做个防抖，防频繁点击。
				clearTimeout(this.getScreensTaskID);
				let my = this;
				this.getScreensTaskID = setTimeout(() => {
					logger.log("getScreensList");
					my.screensList = trtcCloud.getScreenCaptureSources(200, 160, 0, 0);
					my.screensListVisiable = true;
				}, 200);
			},

			/**
			 * 当在 show-screen-capture 组件中选择了一个窗口快照后触发，这里会开始屏幕分享
			 */
			chooseWindowCapture(event) {
				let source = {
					sourceId: event.currentTarget.dataset.id,
					sourceName: event.currentTarget.dataset.name,
					type: parseInt(event.currentTarget.dataset.type),
				};
				logger.log("chooseWindowCapture", source);
				this.startScreenShare(source);
				this.screensListVisiable = false;
				this.isScreenSharing = true;
			},

			startScreenShare(source) {
				let rect = new Rect();
				rect.top = 0;
				rect.left = 0;
				rect.width = 0;
				rect.height = 0;
				trtcCloud.selectScreenCaptureTarget(
					source.type,
					source.sourceId,
					source.sourceName,
					rect,
					true,
					true
				);
				trtcCloud.startScreenCapture();
			},

			stopScreenShare() {
				trtcCloud.stopScreenCapture();
			},

			/**
			 * 离开房间,会退回到入口页面。
			 */
			exitRoom(event) {
        this.$confirm('确定离开会议？', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '离开',
          cancelButtonText: '取消'
        })
          .then(() => {
            logger.log("exitRoom", event);
            trtcCloud.exitRoom();
            let my = this;
            setTimeout(() => {
              my.$router.push("/");
            }, 0);
            this.$message({
              type: 'info',
              message: '已离开会议'
            });
            
          })
          .catch(action => {
             console.log(action)
          });
				
			},
      //结束会议
      endRoom(){
         this.$confirm('确定结束会议？', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '退出',
          cancelButtonText: '取消'
        })
          .then(() => {
            logger.log("endRoom", event);
            this.meetingInfo.status = 1
            updateMeeting(this.meetingInfo).then((response) => {
              console.log(response)
              trtcCloud.exitRoom();
              let my = this;
              setTimeout(() => {
                my.$router.push("/");
              }, 0);
              this.$message({
                type: 'info',
                message: '已退出会议'
              });
               
            });
            
          })
          .catch(action => {
             console.log(action)
          });
      },

			/**
			 * 隐藏摄像头画面
			 */
			hideLocalCameraVideoDom() {
				// document.querySelector('div.local-video-container').style.display = 'none';

				let id = "0";
				let view = document.getElementById(id);
				view.style.display = "none";
			},

			/**
			 * 显示摄像头画面
			 */
			startCameraAndMicDom() {
				// document.querySelector('div.local-video-container').style.display = 'inline-block';
				let id = "0";
				let view = document.getElementById(id);
				view.style.display = "inline-block";
			},

			/**
			 * 启动摄像头、麦克风，显示本地画面
			 */
			startCameraAndMic() {
				// let id = `local_video-${this.roomId}-${TRTCVideoStreamType.TRTCVideoStreamTypeBig}`;
				// logger.log(`startCameraAndMic: ${id}`);
				// let view = document.getElementById(id);
				// if (!view) {
				// 	view = document.createElement('div');
				// 	view.id = id;
				// 	view.className = 'local-video-container';
				// 	this.videoContainer.appendChild(view);
				// }
				let id = "0";
				let view = document.getElementById(id);
				trtcCloud.startLocalPreview(view);
				trtcCloud.startLocalAudio();
				trtcCloud.setLocalViewFillMode(TRTCVideoFillMode.TRTCVideoFillMode_Fill);
			},
			warn(message) {
				logger.warn(message);
			},
			getDefaultCamera() {
				let deviceInfo = trtcCloud.getCurrentCameraDevice();
				if (deviceInfo) {
					this.cameraId = deviceInfo.deviceId;
					console.log(this.cameraId);
				}
			},

			getCameraList() {
				let tmp = trtcCloud.getCameraDevicesList();
				if (tmp.length === 1 && this.selectedCameraID === "") {
					this.cameraId = tmp[0].deviceId;
					console.log(this.cameraId);
				}
				for (var i = 0; i < tmp.length; i++) {
					this.cameraList.push({
						text: tmp[i].deviceName,
						value: tmp[i].deviceId,
					});
				}
				logger.log.apply(logger, ["getCameraList", ...tmp]);
			},
		},
		mounted() {
			// 没有摄像头，有麦克风，可以音频
			if (trtcState.isCameraReady() === false) {
				logger.error(`找不到可用的摄像头`);
				this.$message({
					message: "找不到可用的摄像头，其他用户将无法看到您的画面。",
					type: "warning",
				});
			}
			// 有摄像头，没有麦克风，可以视频
			if (trtcState.isMicReady() === false) {
				logger.error(`找不到可用的麦克风`);
				this.$message({
					message: "找不到可用的麦克风，其他用户将无法听到您的声音。",
					type: "warning",
				});
			}
			// 1. 获取用于承载视频的 HTMLElement；
			this.videoContainer = document.querySelector("#video-container");
			logger.log(`mounted: `, this.$route.params);

			// 获取 vue-router 传参：userId 和 roomId

			let p_roomId = this.$route.query.roomNum;
			let p_meetingInfo = this.$route.query.meetingInfo;
      if(p_meetingInfo){
        this.meetingInfo = p_meetingInfo
      }
      console.log( this.meetingInfo )
      
      if(this.meetingInfo.id){
        if(this.userId == this.meetingInfo.masterId){
          this.showEndMeeting = true
        }
      }else{
        this.showRequestPeoples =true
      }
      console.log(this.showRequestPeoples)
      console.log(this.showEndMeeting)
			this.roomId = parseInt(p_roomId); // roomId 为整数类型
			let p_sdkInfo = this.$route.query.sdkInfo;
			this.sdkInfo = p_sdkInfo;
			console.log("签名 ");
			console.log(this.sdkInfo);
			// this.userId = this.userId.toString(); // userId 为字符串类型
			// this.cameraId = decodeURIComponent("pcamId".toString()); // 摄像头ID
			if (!this.roomId || !this.userId) {
				// this.$bvToast.toast('roomId 或 userId 为空，请填写后再试。');
				// this.$router.push('trtc-index');
				// return;
			}
			// 2. 计算签名
			// this.sdkInfo = genTestUserSig(this.userId);

			// 3. 实例化一个 trtc-electron-sdk
			trtcCloud = new TRTCCloud();
			logger.warn(`sdk version: ${trtcCloud.getSDKVersion()}`);

			this.getDefaultCamera();
			this.getCameraList();
			this.cameraId = decodeURIComponent(this.cameraId.toString()); // 摄像头ID
			console.log("摄像头id 初始化后" + this.cameraId);
			// 4. 配置基本的事件订阅
			trtcCloud.on("onError", this.onError.bind(this));
			trtcCloud.on("onWarning", this.onWarning.bind(this));
			trtcCloud.on("onStatistics", (statis) => {
				logger.log("onStatistics", statis);
			});
			trtcCloud.on("onEnterRoom", this.onEnterRoom.bind(this));
			trtcCloud.on("onExitRoom", this.onExitRoom.bind(this));
			trtcCloud.on("onUserVideoAvailable", this.onUserVideoAvailable.bind(this));
			trtcCloud.on(
				"onRemoteUserEnterRoom",
				this.onRemoteUserEnterRoom.bind(this)
			);
			trtcCloud.on(
				"onRemoteUserLeaveRoom",
				this.onRemoteUserLeaveRoom.bind(this)
			);
			trtcCloud.on(
				"onUserSubStreamAvailable",
				this.onUserSubStreamAvailable.bind(this)
			);
			logger.log(`mounted, setCurrentCameraDevice('${this.cameraId}')`);
			trtcCloud.setCurrentCameraDevice(this.cameraId);
			// 5. 设置编码参数
			// TRTCVideoEncParam 的详细说明，请参考： https://web.sdk.qcloud.com/trtc/electron/doc/zh-cn/trtc_electron_sdk/TRTCVideoEncParam.html
			let encParam = new TRTCVideoEncParam();

			/**
			 *  videoResolution
			 * 【字段含义】 视频分辨率
			 * 【推荐取值】 : Window 和 iMac 建议选择 640 × 360 及以上分辨率，resMode 选择 TRTCVideoResolutionModeLandscape
			 * 【特别说明】 TRTCVideoResolution 默认只能横屏模式的分辨率，例如640 × 360。
			 */
			// encParam.videoResolution = TRTCVideoResolution.TRTCVideoResolution_640_360;
			encParam.videoResolution = TRTCVideoResolution.TRTCVideoResolution_640_360;

			/**
			 * TRTCVideoResolutionMode
			 *【字段含义】分辨率模式（横屏分辨率 - 竖屏分辨率）
			 *【推荐取值】Window 和 Mac 建议选择 TRTCVideoResolutionModeLandscape
			 *【特别说明】如果 videoResolution 指定分辨率 640 × 360，resMode 指定模式为 Portrait，则最终编码出的分辨率为360 × 640。
			 */
			encParam.resMode = TRTCVideoResolutionMode.TRTCVideoResolutionModeLandscape;
			encParam.videoFps = 25;
			encParam.videoBitrate = 600;
			encParam.enableAdjustRes = true;
			trtcCloud.setVideoEncoderParam(encParam);

			// 6. 开启美颜
			// setBeautyStyle 详细信息，请参考：https://web.sdk.qcloud.com/trtc/electron/doc/zh-cn/trtc_electron_sdk/TRTCCloud.html#setBeautyStyle
			trtcCloud.setBeautyStyle(TRTCBeautyStyle.TRTCBeautyStyleNature, 5, 5, 5);

			// 7. 进入房间
			// TRTCParams 详细说明，请查看文档：https://web.sdk.qcloud.com/trtc/electron/doc/zh-cn/trtc_electron_sdk/TRTCParams.html
			let param = new TRTCParams();
			let userIdStr = "";
			userIdStr = this.userId;
			userIdStr = userIdStr.toString();
			param.sdkAppId = this.sdkInfo.sdkappid;
			param.userSig = this.sdkInfo.userSig;
			param.roomId = this.roomId;
			param.userId = userIdStr;
			param.privateMapKey = ""; // 房间签名（非必填），7.1.157 版本以上（含），可以忽略此参数，7.1.157 之前的版本建议赋值为空字符串
			param.businessInfo = ""; // 业务数据（非必填），7.1.157 版本以上（含），可以忽略此参数，7.1.157 之前的版本建议赋值为空字符串
			console.log(param)
			/**
			 * TRTCAppScene.TRTCAppSceneVideoCall: 视频通话场景，适合[1对1视频通话]、[300人视频会议]、[在线问诊]、[视频聊天]、[远程面试]等。
			 */
			trtcCloud.enterRoom(param, TRTCAppScene.TRTCAppSceneVideoCall);
			window.appMonitor?.reportEvent("EnterVideoRoom", "success");

			// 挂到 windows BOM 下，方便调试。
			window.trtc = trtcCloud;
			window.videoEncode = new BDVideoEncode(trtcCloud);
			window.beauty = new BDBeauty(trtcCloud);
		},

		beforeDestroy() {
			this.isScreenSharing = false;
		},
	};
</script>

<style scoped>
	.app-container {
		color: #ffffff;
		padding: 0 10px;
		background-color: #000;
		height: 100vh;
		overflow-x: hidden;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.video-box {
		overflow-x: hidden;
		height: calc(100vh - 80px);
	}

	.video-box div {
		float: left;
	}

	.video-box canvas {
		width: 100%;
		zoom: 0 !important;
		height: 100%;
		object-fit: cover;
	}

	.video-box .two {
		overflow: hidden;
		/* border: 1px solid #ccc; */
		width: calc(50% - 20px);
		height: calc(50% - 20px);
		margin: 10px;
	}

	.video-box .four {
		overflow: hidden;
		/* border: 1px solid #ccc; */
		width: calc(25% - 20px);
		height: calc(25% - 20px);
		margin: 10px;
	}

	.video-box .all {
		overflow: hidden;
		/* border: 1px solid #ccc; */
		width: calc(20% - 20px);
		height: calc(25% - 20px);
		margin: 10px;
	}
</style>
